//
//  LXPlateApplyViewController.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/24.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXPlateApplyViewController.h"
#import "LXTableViewCell.h"
#import "LXRemarkTabelViewCell.h"
#import "LXPlateModel.h"
#import "LXPlatePlanTableViewCell.h"
#import "LXPlatePlanRepaymentView.h"
#import "LXCooperationListViewController.h"
#import "LXCooperationModel.h"

@interface LXPlateApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) UITableView *tableView;
@property (nonatomic) NSMutableArray *data;
@property (nonatomic) NSMutableDictionary *loanDic;
@property (nonatomic) NSDictionary *selDic;

/**支付计划表*/
@property (nonatomic) NSMutableArray *payPlanAry;

@property (nonatomic) NSInteger totalYear; // 总时长

@property (nonatomic) NSString *ownerCompanyId; // 收款公司id


@end

@implementation LXPlateApplyViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self layoutCustomNav:self.view title:@"新增牌照费"];
    
    [self.tableView registerClass:[LXTableViewCell class] forCellReuseIdentifier:NSStringFromClass([LXTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXPlatePlanTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXPlatePlanTableViewCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LXRemarkTabelViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];

    
    
    
    self.view.backgroundColor = White_Color;
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    if (self.type == 1) {
        [self setBottomViewWithText:@"确认新增"];
    }
    else {
        [self setBottomViewWithText:@"确认修改"];
    }
    
    
    
}
- (void)loadData{
    
    self.loanDic  = [NSMutableDictionary dictionary];
    
    self.totalYear = 3;
    
    // 模型为空,说明从车辆详情进入
    if (!ObjectIsEmpty(self.plateModel)) {

        

        // 车牌号
        [self.loanDic setValue:self.plateModel.carNum forKey:@"carNum"];
        [self.loanDic setValue:[NSString stringWithFormat:@"%@年",@(self.totalYear)] forKey:@"totalYear"];
        [self.loanDic setValue:[NSString getNowDateWithFormat:@"yyyy-MM-dd"] forKey:@"startUseDate"];

        [self countDate];
    
        // 修改的时候需要带入数据
        if (self.type==2) {
            
            
            self.totalYear = self.plateModel.totalYear;
            
            [self.loanDic setValue:[NSString stringWithFormat:@"%@年",@(self.totalYear)] forKey:@"totalYear"];
            
            //所属公司
            self.ownerCompanyId = self.plateModel.ownerCompanyId;
            [self.loanDic setValue:self.plateModel.ownerCompanyName forKey:@"ownerCompanyName"];
            //开始日期
            [self.loanDic setValue:self.plateModel.startUseDate forKey:@"startUseDate"];
            //结束开始
            [self.loanDic setValue:self.plateModel.endUseDate forKey:@"endUseDate"];
            //牌照费
            [self.loanDic setValue:[NSString toTen:self.plateModel.price] forKey:@"price"];
            // 计划表
            self.payPlanAry = [NSMutableArray arrayWithArray:self.plateModel.paymentList];
            // 备注
            [self.loanDic setValue:self.plateModel.remark forKey:@"remark"];

        }

    }

    NSArray *ary0 = @[
         
           @{
               @"title":@"车牌号",
               @"key":@"carNum",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*牌照所属":@"牌照所属",
               @"key":@"ownerCompanyName",
               @"placeHolder" : @"请选择车牌所属公司",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickCompanyAction":@"",
               @"height":@(kComHeight)
           },
           @{
               @"title":self.type==1?@"*总时长":@"总时长",
               @"key":@"totalYear",
               @"placeHolder" : @"请选择总时长",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickTotalUseAction":@"",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.type==1?@"*牌照开始日期":@"牌照开始日期",
               @"key":@"startUseDate",
               @"placeHolder" : @"请选择牌照开始日期",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickBeginUseAction":@"",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.type==1?@"*牌照结束日期":@"牌照结束日期",
               @"key":@"endUseDate",
               @"placeHolder" : @"请选择牌照结束日期",
               @"canEdit":@(NO),
               @"showAccess":self.type==1?@(YES):@(NO),
               @"sel":self.type==1?@"clickEndUseAction":@"",
               @"height":@(kComHeight),
           },
           @{
               @"title":self.type==1?@"*牌照费(元/年)":@"牌照费(元/年)",
               @"key":@"price",
               @"placeHolder" : @"请输入牌照费",
               @"inputType":@(NUM_DECIMAL),
               @"keyboardType":@(UIKeyboardTypeDecimalPad),
               @"maxLength":@(7),
               @"sel":@"",
               @"showAccess":@(NO),
               @"canEdit":self.type==1?@(YES):@(NO),
               @"height":@(kComHeight)
           },
    
    ];
    
    [self.data addObject:ary0];
    
    NSArray *ary1 = @[
        @{
            @"title":@"牌照费支付计划",
            @"key":@"planForm",
            @"canEdit":self.type==1?@(YES):@(NO),
            @"height":@([LXPlatePlanTableViewCell getHeight:self.plateModel.paymentList])
        }
    ];
    [self.data addObject:ary1];
  
    
    NSArray *ary2 = @[
        @{
            @"title":@"备注",
            @"key":@"remark",
            @"height":@(150)
        }
    ];
    [self.data addObject:ary2];
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.data.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.data[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    if ([dic[@"key"] isEqualToString:@"planForm"]&&self.type==1) {
        return [LXPlatePlanTableViewCell getHeight:self.payPlanAry];
    }
    return [dic[@"height"] doubleValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    if([dic[@"key"]  isEqualToString:@"remark"]){
        // 备注
        LXRemarkTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXRemarkTabelViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
        cell.textView.placeholder = @"请输入 ~";
        cell.textView.maxLength = 200;
        cell.remarkTitle.text = @"备注";
        cell.textView.text = self.loanDic[@"remark"];
        [cell setTextViewEdit:^(NSString * _Nonnull textStr) {
            [self.loanDic setValue:textStr forKey:@"remark"];
        }];
        return cell;
    }
    // 租金计划表
   else if([dic[@"key"]  isEqualToString:@"planForm"]){
    
        
        if ([dic[@"canEdit"] boolValue]) {
            
            LXPlatePlanTableViewCell *cell = [[LXPlatePlanTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXPlatePlanTableViewCell class]) WithData:!ObjectIsEmpty(self.payPlanAry)?self.payPlanAry:[NSMutableArray array]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setClipsToBounds:YES];
            cell.titleLab.text = dic[@"title"];
            
            
            
            [cell setClickBtnAction:^(LXPlateModel * _Nonnull model) {
                
                // 修改
                [self showPlanViewWithModel:model];
                
            }];
            
            return cell;
        }
        else {
    
            LXPlatePlanTableViewCell *cell = [[LXPlatePlanTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([LXPlatePlanTableViewCell class]) andShowWithData:self.payPlanAry];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setClipsToBounds:YES];
            cell.titleLab.text = dic[@"title"];
            return cell;
           
        }
        
    }
    
    
    LXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([LXTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setClipsToBounds:YES];
    

    cell.cellDic = dic;
    cell.textFiled.hidden = NO;
    cell.subTitleLab.hidden = YES;
    cell.textFiled.text = self.loanDic[dic[@"key"]];
    

    cell.textfiledChangeBlock = ^(NSString * _Nonnull textStr) {
        self.loanDic[dic[@"key"]]  = textStr;
    

        if ([dic[@"key"] isEqualToString:@"price"]) {
            [self payPlanAction];
        }
        
    };
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *dic = self.data[indexPath.section][indexPath.row];
    self.selDic = dic;
    NSString * selName = dic[@"sel"];
    SEL action = NSSelectorFromString(selName);
    if ([self respondsToSelector:action]) {
        [self performSelector:action withObject:nil afterDelay:0];
    }

}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 30)];
    vv.backgroundColor = [UIColor colorWithHexString:@"#F7F8FA"];
    return vv;
}
//MARK: 计算结束日期
-(void)countDate{
    if (!StringIsEmpty(self.loanDic[@"startUseDate"])) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd";
        NSDate *date = [formatter dateFromString:self.loanDic[@"startUseDate"]];
        NSString *pactEndTime = [NSString getCustomDateFromDate:date withMonth:self.totalYear * 12];
        [self.loanDic setValue:pactEndTime forKey:@"endUseDate"];
        [self.tableView reloadData];
    }
}
#pragma mark -- 选择总时长
-(void)clickTotalUseAction{
    [self.view endEditing:YES];
    
    NSArray *ary = @[@"1年",@"2年",@"3年",@"4年",@"5年"];
    SinglePickerView *singPickView = [[SinglePickerView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    for (int i = 0; i<ary.count; i++) {
        if ([self.loanDic[@"totalYear"] isEqualToString:ary[i]]) {
            singPickView.selectInteger = i;
        }
    }
    [singPickView pickViewWithArray:ary andDescArray:nil andTitleStr:@"请选择使用总时长"];
    [[UIApplication sharedApplication].delegate.window addSubview:singPickView];
    [singPickView showBottomView];
    singPickView.block = ^(NSString *singleTitle){
        [self.loanDic setObject:singleTitle forKey:self.selDic[@"key"]];
        
        self.totalYear = [[singleTitle substringWithRange: NSMakeRange(0, 1)] intValue];
        
        [self countDate];
        
        [self.tableView reloadData];
        
        [self payPlanAction];
        
        
    };
    
    
}
#pragma mark -- 选择开始日期
-(void)clickBeginUseAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"startUseDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择牌照开始日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
        [weakSelf.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];

        
        [weakSelf countDate];
        
        [self.tableView reloadData];
        
        [self payPlanAction];

    };
}
#pragma mark -- 选择结束日期
-(void)clickEndUseAction{
    [self.view endEditing:YES];
    DatePickView *datePicker =[[DatePickView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withDateStr:self.loanDic[@"endUseDate"] withIsMaxDate:YES withNoForward:NO WithTips:@"请选择牌照结束日期"] ;
    [datePicker showBoomView];
    [[[UIApplication sharedApplication].delegate window] addSubview:datePicker];
    WEAKSELF
    datePicker.block = ^(NSString *yearString){
        
       

        if([NSString compareDate:yearString withDate:self.loanDic[@"startUseDate"] withFormat:k_DateFormat]==1){
            showAlert(@"结束日期不能大于开始日期");
        }
        else {
            [self.loanDic setObject:yearString forKey:weakSelf.selDic[@"key"]];
        }

    };
}
#pragma mark -- 选择第三方公司
-(void)clickCompanyAction{
    LXCooperationListViewController *vc = [[LXCooperationListViewController alloc] init];
    vc.type = 2;
    [vc setClickVcCallBlock:^(LXCooperationModel * _Nonnull model) {
        
        [self.loanDic setValue:model.name forKey:@"ownerCompanyName"];
        self.ownerCompanyId = model.ID;
        [self.tableView reloadData];
    }];
    [self pushToNextController:vc];
}

- (NSMutableArray *)data{
    if (!_data) {
        _data = [[NSMutableArray alloc]init];
    }
    return _data;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kViewTopHeight, ScreenWidth, kScreenHeight - kViewTopHeight - kComHeight - 10) style:UITableViewStylePlain];
        
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = ColorWithF7F8FA;
        _tableView.sectionFooterHeight = 10;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}




#pragma mark ---- 确认新增/修改点击事件
- (void)clickBottomView:(UIButton *)sender{
    
    if (StringIsEmpty(self.loanDic[@"ownerCompanyName"])) {
        showAlert(@"请选择车牌所属公司");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"ownerCompanyName"])) {
        showAlert(@"请选择车牌所属公司");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"startUseDate"])) {
        showAlert(@"请选择牌照开始日期");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"endUseDate"])) {
        showAlert(@"请选择牌照而技术日期");
        return;
    }
    if (StringIsEmpty(self.loanDic[@"price"])) {
        showAlert(@"请输入牌照费");
        return;
    }
    if ([self.loanDic[@"price"] doubleValue] == 0) {
        showAlert(@"牌照费不能为0");
        return;
    }
   
    
    [Tool showAlertTitle:@"是否确认提交" msg:nil cancelTitle:@"取消" commitBtnTitle:@"确定" cancelHandlerBlock:^{
    } commitHandlerBlock:^{
        
        
        NSMutableArray *paymentList = [NSMutableArray array];
        
        for (LXPlateModel *mm in self.payPlanAry) {
            
            NSDictionary *dic = @{
                @"fundType":@"9",// 牌照费
                @"amount":mm.amount,
                @"exceptPaidDate":mm.exceptPaidDate,
                @"remark":mm.remark,
                @"period":@(mm.period)
            };
            [paymentList addObject:dic];
        }
        
        
        NSMutableDictionary *dic = @{
            
            @"carId":self.plateModel.carId, // 所属车辆id
            @"carNum":self.plateModel.carNum,// 所属车辆车牌号
            @"totalYear":@(self.totalYear),// 总时长
            @"ownerCompanyName":self.loanDic[@"ownerCompanyName"],//  收款公司
            @"ownerCompanyId":self.ownerCompanyId,//  收款公司id
            @"startUseDate":self.loanDic[@"startUseDate"], //  开始日期
            @"endUseDate":self.loanDic[@"endUseDate"], //  结束日期
            @"price":self.loanDic[@"price"], // 牌照金额
            @"remark":self.loanDic[@"remark"], //  备注
            @"paymentList":paymentList, //  计划表
            
        }.mutableCopy;
        
        
        NSString *url;
        if (self.type == 1) {
            url = POST_AddTlicensefee;
        }
        else
        {
            url = POST_UpdateTlicensefee;
            [dic setValue:self.plateModel.ID forKey:@"id"];
        }
        
        
        [MSNetworkManager postRevertUrl:url params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
            if (isSuccess) {
                if (self.type==1) {
                    showAlert(@"新增牌照费成功");
                }
                else {
                    showAlert(@"修改牌照费成功");
                }
               
                
                // carModel 有值说明从详情页进入,返回时须刷新列表
                if (!ObjectIsEmpty(self.plateModel)) {
                    kUserDefaultSetBool(YES, kRefreshStr);
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:YES];
    } onVC:self];
    
 
}



// MARK: 租金支付计划表
-(void)payPlanAction{
    
    
    if (StringIsEmpty(self.loanDic[@"price"]) ||
        StringIsEmpty(self.loanDic[@"startUseDate"])||
        StringIsEmpty(self.loanDic[@"endUseDate"]) ||
        self.totalYear == 0) {
        return;
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd";
//    NSString *nextYY = [self.loanDic[@"startUseDate"] componentsSeparatedByString:@"-"][0];
//    NSString *nextMM = [self.loanDic[@"startUseDate"] componentsSeparatedByString:@"-"][1];
    NSDate *date = [formatter dateFromString:self.loanDic[@"startUseDate"]];

    NSMutableArray *ary = [NSMutableArray array];
    for (int i = 0; i<self.totalYear; i++) {

        NSString *nowDate = [NSString getCustomDateFromDate:date withMonth:12 * i];
        
        NSDictionary *dic = @{
            @"exceptPaidDate":nowDate,
            @"amount":self.loanDic[@"price"],
            @"remark":[NSString stringWithFormat:@"第%d期牌照费",i+1],
            @"period":@(i+1),
        };
        [ary addObject:dic];
    }


    self.payPlanAry = [LXPlateModel mj_objectArrayWithKeyValuesArray:ary];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.data.count-2]  withRowAnimation:UITableViewRowAnimationNone];
}
// MARK: 修改还款计划
-(void)showPlanViewWithModel:(LXPlateModel *)model{
    LXPlatePlanRepaymentView *vc = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LXPlatePlanRepaymentView class]) owner:nil options:nil].firstObject;
    vc.model = model;
    vc.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [self.view addSubview:vc];


    [vc setClickPlanAction:^(LXPlateModel * _Nonnull mm) {

        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.data.count-2]  withRowAnimation:UITableViewRowAnimationNone];

    }];
  
    
    
}


@end
